package com.longy.desensitized.util.filter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.longy.desensitized.util.annotation.DesensitizationField;
import com.longy.desensitized.util.enums.DesensitizedType;

import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Objects;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;


/**
 * 麻木过滤器 脱敏过滤器
 *
 * @author longyang
 * @date 2022/11/07
 */
@AllArgsConstructor
@NoArgsConstructor
public final class DesensitizedFilter extends JsonSerializer<String> implements ContextualSerializer {

    /**
     * 脱敏类型
     */
    private DesensitizedType type;


    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (ObjectUtils.isEmpty(value)) {
            return;
        }
        String val = "";
        switch (type) {
            case NAME:
                val = DesensitizedUtil.chineseName(value);
                break;
            case MOBILE:
                val = DesensitizedUtil.mobilePhone(value);
                break;
            case EMAIL:
                int index = StrUtil.indexOf(value, '@');
                if (index <= 1) {
                    val = DesensitizedUtil.email(value);
                    break;
                }
                val = StrUtil.hide(value, 3, index);
                break;
            case PASSWORD:
                val = DesensitizedUtil.password(value);
                break;
            default:
                val = value;
                break;
        }
        //修改数据
        gen.writeString(val);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property)
            throws JsonMappingException {
        if (ObjectUtils.isEmpty(property)) {
            return prov.findNullValueSerializer(property);
        }
        if (!Objects.equals(property.getType().getRawClass(), String.class)) {
            return prov.findNullValueSerializer(property);
        }
        //是否有注解
        DesensitizationField annotation = property.getAnnotation(DesensitizationField.class);
        if (ObjectUtils.isEmpty(annotation)) {
            return prov.findNullValueSerializer(property);
        }
        //修改值
        return new DesensitizedFilter(annotation.type());
    }
}
